package com.saya.servlet;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.saya.model.User;
import com.saya.model.UserLogin;
import com.saya.response.LoginRs;

@SuppressWarnings("serial")
public class LoginServlet extends HttpServlet {
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("application/json");
		String des = "Ban da dang nhap thanh cong";
		String token = "";
		Boolean status = Boolean.valueOf(false);
		String phoneNumber = req.getParameter("PhoneNumber");
		String deviceId = req.getParameter("DeviceId");
		String password = req.getParameter("Password");

		User user = new User();
		user = user.getUser(phoneNumber);
		if (user != null) {
			if (user.getPassword().equals(password)) {
				UserLogin userLogin = new UserLogin(phoneNumber, deviceId);
				token = userLogin.CreateorUpdate(userLogin);
				if (token == null)
					des = "Loi he thong";
				else
					status = Boolean.valueOf(true);
			} else {
				des = "Sai mat khau";
			}
		} else
			des = "Khong ton tai tai khoan";

		LoginRs rs = new LoginRs();
		if (status.booleanValue())
			rs.setCode("0");
		else {
			rs.setCode("1");
		}
		rs.setMessage(des);
		rs.setPhonenumber(phoneNumber);
		rs.setToken(token);
		Gson gson = new Gson();
		resp.getWriter().println(gson.toJson(rs));
	}
}
